'use strict';

define(function(require,exports,module){
	
	var React = require('react');
	var $ = require('jquery');

	var publicObj = require('lib/public');
	var token = publicObj.get_token();
	
	/*下拉框*/
	var SelectOption = require('components/partial/SelectOption');
	
	/*DATE下拉框*/
	var SelectOptionDate = require('components/partial/SelectOptionDate');
	
	//折线图
	var DayOpenLineDiagram = require('components/diagram/DayOpenLineDiagram');

    //ActiveUserAreaMuliti
    var ActiveUserAreaMuliti = require('components/diagram/AreaDiagram/ActiveUserAreaMuliti');

    /*时间段图表*/
    var DayOpenTimeBucket = require('./DayOpenDiagram/TimeBucket');
    /*Loading状态组件*/
    var ReactLoading = require('../partial/ReactLoading');

	module.exports = React.createClass({displayName: "exports",
		handleDateChange:function(event){
			var date = event.target.value;
			this.setState({'date':date});
            this.setState({'hardware':''});
			this.loadData(date,'');
		},
		handleHardwareChange:function(event){
			var hardware = event.target.value;
			this.setState({'hardware':hardware});
			this.loadData(this.state.date,hardware);
		},
		loadData:function(date,hardware){
			var token = publicObj.get_token();
			this.setState({data:[]});
			if(date && hardware){
				var year = date.substring(0,4);
				var month = date.substring(4,6);
				var day = date.substring(6,8);
				var start_date = new XDate(year+"-"+month+"-"+day+" 00:00:00").toString('yyyy-MM-dd')+' 00:00:00';
				var end_date = new XDate(year+"-"+month+"-"+day+" 00:00:00").addDays(1).toString('yyyy-MM-dd')+' 00:00:00';

                var sql;
                if(hardware == 'iphone'){
                    sql = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(create_time),'%H') as time,count(*) as value\
						  FROM qeeniao.app_info\
						 where platform = 'iOS'\
						   and(create_time>= '"+start_date+"'\
						   and create_time< '"+end_date+"')\
						 group by time\
						 order by time ASC";
                }else if(hardware == 'android'){
                    sql = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(create_time),'%H') as time,count(*) as value\
						  FROM qeeniao.app_info\
						 where platform = 'Android'\
						   and(create_time>= '"+start_date+"'\
						   and create_time< '"+end_date+"')\
						 group by time\
						 order by time ASC";
                }

				$.ajax({
					url:this.props.url,
					data:{sql:sql,'access_token':token},
					type:'post',
					dataType:'json',
					success:function(o){
						var tmp = [];
						tmp.push(o);
						if(o){
							if(this.isMounted()) {
                                this.setState({'data': tmp});
                            }
						}

					}.bind(this),
					error:function(xhr,status,err){
						console.error(sql,status,err.toString());
					}.bind(this)
				});
			}
		},
		getInitialState:function(){
			var date = new XDate().addDays(-10).toString("yyyyMMdd");
            var android_sql = "SELECT thedate AS name,\
								count(DISTINCT device_key) AS value\
								FROM qeeniao.app_info\
								WHERE platform = 'Android'\
								AND thedate >= "+date+"\
								GROUP BY name\
								ORDER BY name ASC";

            var ios_sql = "SELECT thedate AS name,\
							count(DISTINCT device_key) AS value\
							FROM qeeniao.app_info\
							WHERE platform = 'iOS'\
							AND thedate >="+date+"\
							GROUP BY name\
							ORDER BY name ASC";

			return {
				'data':[],
                'all_data':{'ios':[],'android':[]},
				'date':'',
				'ajax_data':{'android_sql':android_sql,'ios_sql':ios_sql,'access_token':token}
			}
		},
        createHandle:function(){
            $('#DayOpenTimeBucket').modal();
        },
        updateRender:function(){
        	this.setState({'ajax_data':''});
        	var date = new XDate().addDays(-10).toString("yyyyMMdd");
            var android_sql = "SELECT thedate AS name,\
								count(DISTINCT device_key) AS value\
								FROM qeeniao.app_info\
								WHERE platform = 'Android'\
								AND thedate >= "+date+"\
								GROUP BY name\
								ORDER BY name ASC";

            var ios_sql = "SELECT thedate AS name,\
							count(DISTINCT device_key) AS value\
							FROM qeeniao.app_info\
							WHERE platform = 'iOS'\
							AND thedate >="+date+"\
							GROUP BY name\
							ORDER BY name ASC";
			this.setState({'ajax_data':{'android_sql':android_sql,'ios_sql':ios_sql,'access_token':token}});
        },
		render:function(){
            var diagram;

            if(this.state.data.length > 0){
                diagram = this.state.data.map(function(item){
                    return (
                        React.createElement(DayOpenLineDiagram, {className: "", id: "DevicePie", id_name: "DevicePie", title: "每日活跃用户数", yName: "活跃用户数", yUnit: "（时/次数）", url: "", data: item})
                    );
                });
            }else{
            	diagram = React.createElement(ActiveUserAreaMuliti, {className: "", id: "AreaMutilDiagram", id_name: "AreaMutilDiagram", y: "活跃用户数", title: "活跃用户数", url: this.props.url, ajax_data: this.state.ajax_data, interval: "300000"});
            }

			return (
				React.createElement("div", {className: "col-xs-6"}, 
					React.createElement("div", {className: "row bgwhite"}, 
						React.createElement("div", {className: "col-xs-3 bs-callout bs-callout-info"}, 
							React.createElement("h4", null, this.props.title, ": ")
						), 
						React.createElement("div", {className: "col-xs-3 "}, 
							React.createElement(SelectOptionDate, {handleDateChange: this.handleDateChange, data: this.props.data, default_value: "选择日期"})
						), 
						React.createElement("div", {className: "col-xs-3"}, 
							React.createElement(SelectOption, {selectValue: this.state.hardware, handleChange: this.handleHardwareChange, data: this.props.hardware_data, formClass: "hardwareForm", default_value: "设备分类"})
						), 
						React.createElement("div", {className: "col-xs-3", style: {margin:'4px 0'}}, 
                            React.createElement("button", {onClick: this.createHandle, className: "btn btn-primary btn", "data-toggle": "modal", "data-target": "#DayOpenTimeBucket"}, "更多")
						), 
                        React.createElement(DayOpenTimeBucket, {id: "DayOpenTimeBucket", url: this.props.url})

					), 
					React.createElement("div", {className: "row"}, 
					diagram
					)
				)
			);
		}
	});

});